<%--
  Created by IntelliJ IDEA.
  User: Tong-dev
  Date: 2015-12-25
  Time: 18:05
--%>

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>Mail index</title>
    <meta name="layout" content="mui"/>
    <style>
    html,
    body {
        background-color: #efeff4;
    }

    .un-readed {
        font-weight: bold;
    }

    .mui-off-canvas-right {
        color: #fff;
    }

    .title {
        margin: 35px 15px 10px;
    }

    .title + .content {
        margin: 10px 15px 35px;
        color: #bbb;
        text-indent: 1em;
        font-size: 14px;
        line-height: 24px;
    }

    input {
        color: #000;
    }
    </style>
</head>

<body>
<!--侧滑菜单容器-->
<div id="offCanvasWrapper" class="mui-off-canvas-wrap mui-draggable">
    <!--菜单部分-->
    <aside id="offCanvasSide" class="mui-off-canvas-left">
        <div id="offCanvasSideScroll" class="mui-scroll-wrapper">
            <div class="mui-scroll">
                <ul class="mui-table-view mui-table-view-chevron mui-table-view-inverted">
                    <g:each in="${folderList}" var="folder">
                        <li class="mui-table-view-cell">
                            <span class="mui-icon ${folder.icon}"></span>${folder.name}
                            <span class="mui-badge ${folder.badgeStyle}">${folder.messageCount}</span>
                        </li>
                    </g:each>
                </ul>

            </div>
        </div>
    </aside>

    <div class="mui-inner-wrap">

        <div id="offCanvasContentScroll" class="mui-content mui-scroll-wrapper">

            <div class="mui-scroll">

                <ul id="mui-mail-list" class="mui-table-view">

                    <g:each in="${mailData.messageList}" var="message">
                        <li id="${message.uid}" class="mui-table-view-cell mui-media ${message.readed ?: 'un-readed'}">
                            <div class="mui-slider-right mui-disabled">
                                <a class="mui-btn mui-btn-red">删除</a>
                            </div>
                            %{--<img class="mui-media-object mui-pull-left" src="../images/cbd.jpg">--}%
                            <div class="mui-media-body mui-slider-handle">
                                ${message?.from}
                                <span class="mui-pull-right">${message.sendDate}</span>

                                <p class='mui-ellipsis'>${message?.subject}</p>
                            </div>

                        </li>
                    </g:each>
                </ul>
            </div>
        </div>
        <!-- off-canvas backdrop -->
        <div class="mui-off-canvas-backdrop"></div>
    </div>
</div>
<asset:javascript src="cookie.js"/>
<script>
    var folder = "${mailData.folderName}", folderMessageCount = ${mailData.messageCount},
            pullDownStartNum =${mailData.pullDownStartNum}, pullUpStartNum = ${mailData.pullUpStartNum};
    mui.init({
        gestureConfig:{
            tap: true, //默认为true
            doubletap: true, //默认为false
            longtap: true, //默认为false
            swipe: true, //默认为true
            drag: true, //默认为true
            hold:false,//默认为false，不监听
            release:false//默认为false，不监听
        },
        swipeBack: false,
        pullRefresh: {
            container: "#offCanvasContentScroll",
            down: {
                contentdown: "下拉可以刷新",
                contentover: "释放立即刷新",
                contentrefresh: "正在刷新...",
                callback: pulldownRefresh
            },
            up: {
                callback: pullUpRefresh
            }
        }
    });
    var btnArray = ['确认','取消'];
    (function ($) {
        $('#mui-mail-list').on('tap', '.mui-btn', function(event) {
            var elem = this;
            var li = elem.parentNode.parentNode;
            mui.confirm('确认删除该条记录？', '招邮', btnArray, function(e) {
                if (e.index == 0) {
                    li.parentNode.removeChild(li);
                } else {
                    setTimeout(function() {
                        $.swipeoutClose(li);
                    }, 0);
                }
            });
        });
    })(mui)
    mui(".mui-table-view").on('tap','.mui-table-view-cell',function(){
//        alert(this.getAttribute("id"));
        var uid = this.getAttribute("id")
        mui.openWindow({
            url: '${createLink(action: "show")}?folder='+folder+"&uid="+uid,
            id:'info'
        });
    })
    /**
     * 下拉刷新具体业务实现
     */
    function pulldownRefresh() {

        mui.ajax('${createLink(action:"getMailCount")}', {
            data: {
                folder: folder
            },
            dataType: 'json',//服务器返回json格式数据
            type: 'post',//HTTP请求类型
            timeout: 10000,//超时时间设置为10秒；
            success: function (data) {
                var messageCount = data.messageCount
                if (messageCount > folderMessageCount) {
                    mui.ajax('${createLink(action:"getMailData")}', {
                        data: {
                            folder: folder,
                            startNum: pullDownStartNum,
                            endNum: messageCount
                        },
                        dataType: 'json',
                        type: 'post',
                        timeout: 10000,
                        success: function (data) {
                            folderMessageCount = data.messageCount
                            pullDownStartNum = folderMessageCount+1
                            var table = document.body.querySelector('#mui-mail-list');
                            mui.each(data.messageList,function(index,item){
                                table.insertBefore(createMessageElement(item), table.firstChild);
                            })

                            mui('#offCanvasContentScroll').pullRefresh().endPulldownToRefresh();
                        },
                        error: function (xhr, type, errorThrown) {
                            //异常处理；
                            console.log(type);
                        }
                    });

                } else {
                    mui('#offCanvasContentScroll').pullRefresh().endPulldownToRefresh();
                }
            },
            error: function (xhr, type, errorThrown) {
                //异常处理；
                console.log(type);
            }
        });

    }

    function pullUpRefresh() {

        mui.ajax('${createLink(action:"getMailData")}', {
            data: {
                folder: folder,
                startNum: pullUpStartNum,
                endNum: pullUpStartNum+9
            },
            dataType: 'json',//服务器返回json格式数据
            type: 'post',//HTTP请求类型
            timeout: 10000,//超时时间设置为10秒；
            success: function (data) {
                folderMessageCount = data.messageCount
                pullUpStartNum = (data.startNum-10)>0?(data.startNum-10):1;
                var table = document.body.querySelector('#mui-mail-list');
                mui.each(data.messageList,function(index,item){
                    table.appendChild(createMessageElement(item));
                })

                mui('#offCanvasContentScroll').pullRefresh().endPullupToRefresh();
            },
            error: function (xhr, type, errorThrown) {
                //异常处理；
                console.log(type);
            }
        });







    }

    function createMessageElement(messageItem) {
        var messageHtml = messageItem.from;
        messageHtml += '<span class="mui-pull-right">';
        messageHtml += messageItem.sendDate;
        messageHtml += '</span> <p class="mui-ellipsis">';
        messageHtml += messageItem.subject;
        messageHtml += '</p>';
        var messageDiv = createElement("div", "[class:mui-media-body  mui-slider-handle]", messageHtml)
        var swipeDiv = createElement("div", "[class:mui-slider-right mui-disabled]", '<a class="mui-btn mui-btn-red">删除</a>')
        var messageElement = createElement("li", "[id:"+messageItem.uid+"][class:mui-table-view-cell mui-media " + (messageItem.readed ? '' : 'un-readed') + ']', [swipeDiv,messageDiv])
        return messageElement
    }

    //侧滑容器父节点
    var offCanvasWrapper = mui('#offCanvasWrapper');
    //主界面容器
    var offCanvasInner = offCanvasWrapper[0].querySelector('.mui-inner-wrap');
    //菜单容器
    var offCanvasSide = document.getElementById("offCanvasSide");
    //Android暂不支持整体移动动画
    if (!mui.os.android) {
        var spans = document.querySelectorAll('.android-only');
        for (var i = 0, len = spans.length; i < len; i++) {
            spans[i].style.display = "none";
        }
    }
    //侧滑容器的class列表，增加.mui-slide-in即可实现菜单移动、主界面不动的效果；
    var classList = offCanvasWrapper[0].classList;
    //变换侧滑动画移动效果；
    mui('.mui-input-group').on('change', 'input', function () {
        if (this.checked) {
            offCanvasSide.classList.remove('mui-transitioning');
            offCanvasSide.setAttribute('style', '');
            classList.remove('mui-slide-in');
            classList.remove('mui-scalable');
            //整体滑动时，侧滑菜单在inner-wrap内
            offCanvasInner.insertBefore(offCanvasSide, offCanvasInner.firstElementChild);
            offCanvasWrapper.offCanvas().refresh();
        }
    });

    //主界面和侧滑菜单界面均支持区域滚动；
    mui('#offCanvasSideScroll').scroll();
    mui('#offCanvasContentScroll').scroll();
    //实现ios平台的侧滑关闭页面；
    if (mui.os.plus && mui.os.ios) {
        offCanvasWrapper[0].addEventListener('shown', function (e) { //菜单显示完成事件
            plus.webview.currentWebview().setStyle({
                'popGesture': 'none'
            });
        });
        offCanvasWrapper[0].addEventListener('hidden', function (e) { //菜单关闭完成事件
            plus.webview.currentWebview().setStyle({
                'popGesture': 'close'
            });
        });
    }

    dd.ready(function () {
        <dd:config agentId="13305008" nonceStr="abcdefg"
               jsApiList="['device.notification.alert', 'device.notification.confirm', 'biz.navigation.setLeft','biz.navigation.setIcon',
                           'biz.navigation.setRight', 'biz.navigation.setTitle', 'runtime.info','runtime.permission.requestAuthCode']"/>


        dd.biz.navigation.setTitle({
            title: '招邮',
            onSuccess: function (result) {

            },
            onFail: function (err) {
            }
        });
        dd.biz.navigation.setIcon({
            showIcon: false,//是否显示icon
            iconIndex: 1,//显示的iconIndex,如图
            onSuccess: function (result) {
                /*结构
                 {
                 }*/
                //点击icon之后将会回调这个函数
            },
            onFail: function (err) {
                //jsapi调用失败将会回调此函数
            }
        });


        dd.biz.navigation.setRight({
            show: true,//控制按钮显示， true 显示， false 隐藏， 默认true
            control: true,//是否控制点击事件，true 控制，false 不控制， 默认false
            text: '文件夹',//控制显示文本，空字符串表示显示默认文本
            onSuccess: function (result) {
                offCanvasWrapper.offCanvas('show');
            },
            onFail: function (err) {
            }
        });


    });
</script>
</body>
</html>